<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>默认首页</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入 ECharts -->
    <script src="../../js/echarts.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #f5f7fa;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
        }
        .page-container {
            padding: 20px;
            max-width: 1400px;
            margin: 0 auto;
        }
        .page-title {
            margin-bottom: 10px;
            color: #1890ff;
            border-bottom: 2px solid #e6f7ff;
            padding-bottom: 10px;
        }
        .statistic-row {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        .statistic-col {
            flex: 1;
        }
        .statistic-item {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
            border-left: 4px solid #1890ff;
        }
        .statistic-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        .statistic-value {
            font-size: 28px;
            font-weight: bold;
            margin: 10px 0;
        }
        .statistic-label {
            color: #8c8c8c;
            font-size: 14px;
        }
        .statistics-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .refresh-btn {
            padding: 8px 15px;
            font-size: 14px;
        }
        .tab-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            padding: 20px;
            margin-top: 20px;
        }
        .date-filter {
            text-align: center;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
        }
        .date-filter label {
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
        }
        .date-filter input {
            padding: 8px 12px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            width: 160px;
        }
        .chart-container {
            width: 100%;
            height: 400px;
            margin-bottom: 20px;
        }
        .chart-row {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }
        .chart-card {
            flex: 1;
            min-width: 500px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            padding: 20px;
            border-top: 3px solid #1890ff;
        }
        .chart-title {
            margin-bottom: 15px;
            color: #303133;
            font-size: 16px;
            font-weight: bold;
            display: flex;
            align-items: center;
        }
        .chart-title i {
            margin-right: 8px;
            color: #1890ff;
        }
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 300px;
            flex-direction: column;
        }
        .empty-data {
            text-align: center;
            padding: 40px;
            color: #8c8c8c;
        }
        .empty-data i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #c0c4cc;
        }
        @media (max-width: 768px) {
            .statistic-row {
                flex-direction: column;
            }
            .chart-card {
                min-width: 100%;
            }
            .date-filter {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <div class="page-container">
        <!-- 页面标题和刷新按钮 -->
        <div class="statistics-header">
            <h1 class="page-title">鲜时蔬管理系统</h1>
            <el-button type="primary" class="refresh-btn" @click="refreshData" :loading="refreshing">
                <i class="el-icon-refresh"></i> {{refreshing ? '刷新中...' : '刷新数据'}}
            </el-button>
        </div>

        <!-- 统计概览 -->
        <div class="statistic-row">
            <div class="statistic-col">
                <div class="statistic-item">
                    <div class="statistic-label">总店铺数</div>
                    <div class="statistic-value">{{ totalShops || 0 }}</div>
                </div>
            </div>
            <div class="statistic-col">
                <div class="statistic-item">
                    <div class="statistic-label">正常店铺</div>
                    <div class="statistic-value" style="color: #52c41a">{{ normalShops || 0 }}</div>
                </div>
            </div>
            <div class="statistic-col">
                <div class="statistic-item">
                    <div class="statistic-label">待审核店铺</div>
                    <div class="statistic-value" style="color: #faad14">{{ pendingAuditShops || 0 }}</div>
                </div>
            </div>
            <div class="statistic-col">
                <div class="statistic-item">
                    <div class="statistic-label">已通过审核</div>
                    <div class="statistic-value" style="color: #1890ff">{{ approvedShops || 0 }}</div>
                </div>
            </div>
        </div>

        <!-- 选项卡容器 -->
        <div class="tab-container">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="订单统计" name="order">
                    <!-- 订单统计内容 -->
                    <div class="date-filter">
                        <label>开始日期: <input type="date" v-model="startDate"></label>
                        <label>结束日期: <input type="date" v-model="endDate"></label>
                        <el-button type="primary" @click="loadOrderData" :loading="loadingOrderData">查询</el-button>
                        <el-button @click="setDefaultDateRange">最近7天</el-button>
                    </div>

                    <div class="chart-row">
                        <!-- 订单金额趋势图 -->
                        <div class="chart-card">
                            <div class="chart-title"><i class="el-icon-trend-charts"></i> 订单金额趋势</div>
                            <div id="trendChart" class="chart-container"></div>
                            <div v-if="!trendDataLoaded" class="empty-data">
                                <i class="el-icon-data-line"></i>
                                <p>暂无数据</p>
                            </div>
                        </div>

                        <!-- 订单状态分布图 -->
                        <div class="chart-card">
                            <div class="chart-title"><i class="el-icon-pie-chart"></i> 订单状态分布</div>
                            <div id="statusChart" class="chart-container"></div>
                            <div v-if="!statusDataLoaded" class="empty-data">
                                <i class="el-icon-pie-chart"></i>
                                <p>暂无数据</p>
                            </div>
                        </div>

                        <!-- 商品销售排行 -->
                        <div class="chart-card">
                            <div class="chart-title"><i class="el-icon-s-data"></i> 商品销售排行</div>
                            <div id="productChart" class="chart-container"></div>
                            <div v-if="!productDataLoaded" class="empty-data">
                                <i class="el-icon-s-data"></i>
                                <p>暂无数据</p>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
<!--                <el-tab-pane label="店铺统计" name="shop">-->
<!--                    &lt;!&ndash; 可以在这里添加更多店铺相关的统计图表 &ndash;&gt;-->
<!--                    <div style="text-align: center; padding: 50px;">-->
<!--                        <i class="el-icon-office-building" style="font-size: 48px; color: #c0c4cc;"></i>-->
<!--                        <h3>店铺统计功能开发中...</h3>-->
<!--                        <p>这里可以添加店铺相关的更多统计图表和分析</p>-->
<!--                    </div>-->
<!--                </el-tab-pane>-->
            </el-tabs>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            // 设置默认日期范围（最近7天）
            const today = new Date();
            const startDate = new Date(today);
            startDate.setDate(today.getDate() - 7);

            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            return {
                totalShops: 0,
                normalShops: 0,
                pendingAuditShops: 0,
                approvedShops: 0,
                activeTab: 'order',
                startDate: formatDate(startDate),
                endDate: formatDate(today),
                trendChart: null,
                statusChart: null,
                productChart: null,
                refreshing: false,
                loadingOrderData: false,
                trendDataLoaded: false,
                statusDataLoaded: false,
                productDataLoaded: false
            };
        },
        mounted() {
            // 页面加载时获取数据
            this.refreshData();

            // 初始化图表
            this.$nextTick(() => {
                this.trendChart = echarts.init(document.getElementById('trendChart'));
                this.statusChart = echarts.init(document.getElementById('statusChart'));
                this.productChart = echarts.init(document.getElementById('productChart'));

                // 加载订单数据
                this.loadOrderData();
            });

            // 响应式调整
            window.addEventListener('resize', () => {
                if (this.trendChart) this.trendChart.resize();
                if (this.statusChart) this.statusChart.resize();
                if (this.productChart) this.productChart.resize();
            });
        },
        methods: {
            refreshData() {
                this.refreshing = true;

                // 显示加载状态
                this.$message({
                    message: '正在刷新数据...',
                    type: 'info',
                    duration: 800
                });

                // 同时请求所有统计数据
                Promise.all([
                    this.getShopCount(),
                    this.getShopStatusCount(),
                    this.getShopAuditStatusCount()
                ]).then(() => {
                    this.$message({
                        message: '数据刷新成功',
                        type: 'success',
                        duration: 800
                    });
                    this.refreshing = false;
                }).catch(error => {
                    this.$message.error('数据刷新失败：' + error.message);
                    this.refreshing = false;
                });
            },
            // 获取总店铺数
            getShopCount() {
                return axios.get(`/vegetablemarketexpress/shop/getShopCount`)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.totalShops = response.data.data;
                        } else {
                            this.$message.error('获取总店铺数失败');
                        }
                    })
                    .catch(error => {
                        console.error('获取总店铺数失败:', error);
                        this.$message.error('获取总店铺数失败');
                    });
            },
            // 获取店铺状态统计（正常/停用）
            getShopStatusCount() {
                return axios.get('/vegetablemarketexpress/shop/statusCount')
                    .then(response => {
                        if (response.data) {
                            const data = response.data;
                            data.forEach(item => {
                                // 更新正常店铺数量（状态0为正常）
                                if (item.status === '0') {
                                    this.normalShops = item.count;
                                }
                            });
                        } else {
                            this.$message.error('获取店铺状态统计失败');
                        }
                    })
                    .catch(error => {
                        console.error('获取店铺状态统计失败:', error);
                        this.$message.error('获取店铺状态统计失败');
                    });
            },
            // 获取店铺审核状态统计
            getShopAuditStatusCount() {
                return axios.get('/vegetablemarketexpress/shop/auditStatusCount')
                    .then(response => {
                        if (response.data) {
                            const data = response.data;
                            data.forEach(item => {
                                if (item.auditStatus === '0') {
                                    // 待审核店铺
                                    this.pendingAuditShops = item.count;
                                } else if (item.auditStatus === '1') {
                                    // 已通过审核店铺
                                    this.approvedShops = item.count;
                                }
                            });
                        } else {
                            this.$message.error('获取店铺审核状态统计失败');
                        }
                    })
                    .catch(error => {
                        console.error('获取店铺审核状态统计失败:', error);
                        this.$message.error('获取店铺审核状态统计失败');
                    });
            },
            // 选项卡切换
            handleTabClick(tab) {
                if (tab.name === 'order') {
                    this.$nextTick(() => {
                        this.loadOrderData();
                    });
                }
            },
            // 设置默认日期范围
            setDefaultDateRange() {
                const today = new Date();
                const startDate = new Date(today);
                startDate.setDate(today.getDate() - 7);

                const formatDate = (date) => {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`;
                };

                this.startDate = formatDate(startDate);
                this.endDate = formatDate(today);
                this.loadOrderData();
            },
            // 加载订单数据
            loadOrderData() {
                if (!this.startDate || !this.endDate) {
                    this.$message.warning('请选择日期范围');
                    return;
                }

                this.loadingOrderData = true;

                Promise.all([
                    this.loadTrendData(),
                    this.loadStatusData(),
                    this.loadProductData()
                ]).then(() => {
                    this.loadingOrderData = false;
                }).catch(() => {
                    this.loadingOrderData = false;
                });
            },
            // 加载趋势数据
            loadTrendData() {
                return axios.get(`/vegetablemarketexpress/order/statistics/trend?startDate=${this.startDate}&endDate=${this.endDate}`)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            const data = response.data.data;

                            if (data && data.length > 0) {
                                const dates = data.map(item => item.date);
                                const amounts = data.map(item => parseFloat(item.totalAmount));
                                const counts = data.map(item => parseInt(item.orderCount));

                                const option = {
                                    tooltip: {
                                        trigger: 'axis'
                                    },
                                    legend: {
                                        data: ['订单金额', '订单数量']
                                    },
                                    xAxis: {
                                        type: 'category',
                                        data: dates
                                    },
                                    yAxis: [
                                        {
                                            type: 'value',
                                            name: '金额(元)'
                                        },
                                        {
                                            type: 'value',
                                            name: '订单数'
                                        }
                                    ],
                                    series: [
                                        {
                                            name: '订单金额',
                                            type: 'line',
                                            data: amounts,
                                            smooth: true,
                                            itemStyle: {
                                                color: '#1890ff'
                                            }
                                        },
                                        {
                                            name: '订单数量',
                                            type: 'bar',
                                            yAxisIndex: 1,
                                            data: counts,
                                            itemStyle: {
                                                color: '#52c41a'
                                            }
                                        }
                                    ]
                                };

                                this.trendChart.setOption(option);
                                this.trendDataLoaded = true;
                            } else {
                                this.trendDataLoaded = false;
                            }
                        } else {
                            this.$message.error('加载趋势数据失败');
                            this.trendDataLoaded = false;
                        }
                    })
                    .catch(error => {
                        console.error('加载趋势数据失败:', error);
                        this.$message.error('加载趋势数据失败');
                        this.trendDataLoaded = false;
                    });
            },
            // 加载状态数据
            loadStatusData() {
                return axios.get('/vegetablemarketexpress/order/statistics/status')
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            const data = response.data.data;

                            if (data && data.length > 0) {
                                const chartData = data.map(item => ({
                                    name: item.statusName,
                                    value: parseInt(item.count)
                                }));

                                const option = {
                                    tooltip: {
                                        trigger: 'item'
                                    },
                                    legend: {
                                        top: 'bottom'
                                    },
                                    series: [
                                        {
                                            name: '订单状态',
                                            type: 'pie',
                                            radius: ['40%', '70%'],
                                            data: chartData,
                                            emphasis: {
                                                itemStyle: {
                                                    shadowBlur: 10,
                                                    shadowOffsetX: 0,
                                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                                }
                                            }
                                        }
                                    ]
                                };

                                this.statusChart.setOption(option);
                                this.statusDataLoaded = true;
                            } else {
                                this.statusDataLoaded = false;
                            }
                        } else {
                            this.$message.error('加载状态数据失败');
                            this.statusDataLoaded = false;
                        }
                    })
                    .catch(error => {
                        console.error('加载状态数据失败:', error);
                        this.$message.error('加载状态数据失败');
                        this.statusDataLoaded = false;
                    });
            },
            // 加载商品排行数据
            loadProductData() {
                return axios.get('/vegetablemarketexpress/order/statistics/product-ranking?limit=10')
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            const data = response.data.data;

                            if (data && data.length > 0) {
                                const productNames = data.map(item => item.productName);
                                const quantities = data.map(item => parseFloat(item.totalQuantity));

                                const option = {
                                    tooltip: {
                                        trigger: 'axis',
                                        axisPointer: {
                                            type: 'shadow'
                                        }
                                    },
                                    xAxis: {
                                        type: 'value'
                                    },
                                    yAxis: {
                                        type: 'category',
                                        data: productNames
                                    },
                                    series: [
                                        {
                                            name: '销售量',
                                            type: 'bar',
                                            data: quantities,
                                            itemStyle: {
                                                color: '#faad14'
                                            }
                                        }
                                    ]
                                };

                                this.productChart.setOption(option);
                                this.productDataLoaded = true;
                            } else {
                                this.productDataLoaded = false;
                            }
                        } else {
                            this.$message.error('加载商品数据失败');
                            this.productDataLoaded = false;
                        }
                    })
                    .catch(error => {
                        console.error('加载商品数据失败:', error);
                        this.$message.error('加载商品数据失败');
                        this.productDataLoaded = false;
                    });
            }
        }
    });
</script>
</body>
</html>